package com.ls.bpmn.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.bpmn.dto.TaskDTO;
import com.ls.bpmn.from.TaskDoneQueryForm;
import com.ls.bpmn.from.TaskQueryForm;
import com.ls.bpmn.service.IProcessService;
import com.ls.common.Constast;
import com.ls.common.ResultObj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lisheng
 * @Date 2025/05/07 10:05
 **/
@RestController
@RequestMapping("/task")
public class TaskController {
    private static final Logger log = LoggerFactory.getLogger(TaskController.class);

    @Autowired
    private IProcessService processService;

    /**
     * 获取待处理任务列表
     * @param form
     * @return
     */
    @PostMapping("/todo")
    public ResultObj todo(@RequestBody TaskQueryForm form) {
        try {
            Page<TaskDTO> page = this.processService.todo(form);
            Map<String, Object> data = new HashMap<>();
            data.put("total", page.getTotal());
            // 处理 records 为空的情况
            data.put("records", page.getRecords() != null ? page.getRecords() : Collections.emptyList());
            return new ResultObj(Constast.OK, "操作成功！", data);
        } catch (Exception e) {
            // 异常时返回空数据
            Map<String, Object> data = new HashMap<>();
            data.put("total", 0);
            data.put("records", Collections.emptyList());
            return new ResultObj(Constast.ERROR, "操作失败：" + e.getMessage(), data);
        }
    }

    @PostMapping("/done")
    public ResultObj done(@RequestBody TaskDoneQueryForm form) {
        try {
            Page<TaskDTO> page = this.processService.done(form);
            Map<String, Object> data = new HashMap<>();
            data.put("total", page.getTotal());
            data.put("records", page.getRecords() != null ? page.getRecords() : Collections.emptyList());
            return new ResultObj(Constast.OK, "操作成功！", data);
        } catch (Exception e) {
            log.error("获取已处理任务异常：{}", e);
            Map<String, Object> data = new HashMap<>();
            data.put("total", 0);
            data.put("records", Collections.emptyList());
            return new ResultObj(Constast.ERROR, "操作失败：" + e.getMessage(), data);
        }
    }
}
